package com.enfo.zjabank.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.enfo.zjabank.dao.PrintDao;
import com.enfo.zjabank.tool.StringUtil;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhoum on 2016/7/27.
 */
@Service
public class PrintServiceImpl implements PrintService {
    private static Logger logger = LoggerFactory.getLogger(PrintServiceImpl.class);
    @Autowired
    private PrintDao printDao;

    @Override
    public String print(HttpServletRequest request,String busi_type,String cust_type){
        String debt_id = request.getParameter("id");
        String sql = null;
        String url = null;
        Map<String,Object> debtMap = new HashMap<>();

        if("new".equals(busi_type) || "change".equals(busi_type)) {//附表1
            if("1".equals(cust_type)){
                debtMap = printDao.getCompanyApply(debt_id,busi_type);
//                主要股东
                String stockholder = (String) debtMap.get("stockholder");
                if(!StringUtil.isEmpty(stockholder)){
                    debtMap.put("stockholder",encodeText(stockholder,"s_name"));
                }
//                其他关联人
                String relv_person = (String) debtMap.get("relv_person");
                if(!StringUtil.isEmpty(relv_person)){
                    debtMap.put("relv_person",encodeText(relv_person,"s_name"));
                }
                url = "print/CompanyApply";
            }else if("0".equals(cust_type)){
                try {
                    debtMap = printDao.getPersonApply(debt_id,busi_type);
                } catch (Exception e) {
                    logger.error("个人逃废债打印取值出错",e);
                }
                url = "print/PersonApply";
            }
//                保证人信息
            String grt_info = (String) debtMap.get("grt_info");
            if(!StringUtil.isEmpty(grt_info)){
                debtMap.put("grt_info",encodeText(grt_info,"s_name"));
            }
//                对外担保情况
            String provd_grt = (String) debtMap.get("provd_grt");
            if(!StringUtil.isEmpty(provd_grt)){
                debtMap.put("provd_grt",encodeText(provd_grt,"g_type"));
            }
//                被申报人逃废银行债务的主要事实（注明符合《机制》惩罚对象的哪类行为）
            String debt_fact = (String) debtMap.get("debt_fact");
            if(!StringUtil.isEmpty(debt_fact)){
                debtMap.put("debt_fact",debt_fact.split(","));
                Map<String,String> debtFactDict = printDao.getDict("debt_fact");
                debtMap.put("debtFactDict",debtFactDict);
            }
//                申报单位要求联合制裁的方式
            String sanction_mode = (String) debtMap.get("sanction_mode");
            if(!StringUtil.isEmpty(sanction_mode)){
                debtMap.put("sanction_mode",sanction_mode.split(","));
            }
//                融资情况表 --> 保证人信息
            String debt_info = (String) debtMap.get("debt_info");
            if(!StringUtil.isEmpty(debt_info)){
//                List<Map<String,Object>> debtInfoList = JSON.parseObject(debt_info, new TypeReference<List<Map<String, Object>>>() {});
                List<Map<String,Object>> debtInfoList = jsonToListMap(debt_info);
                debtMap.put("debt_info",debtInfoList);
            }
        }else if("cancel".equals(busi_type)){
            if("1".equals(cust_type)){
                debtMap = printDao.getCompanyCancel(debt_id);
//                主要股东
                String stockholder = (String) debtMap.get("stockholder");
                if(!StringUtil.isEmpty(stockholder)){
                    debtMap.put("stockholder",encodeText(stockholder,"s_name"));
                }
//                其他关联人
                String relv_person = (String) debtMap.get("relv_person");
                if(!StringUtil.isEmpty(relv_person)){
                    debtMap.put("relv_person",encodeText(relv_person,"s_name"));
                }
                url = "print/CompanyCancel";
            }else if("0".equals(cust_type)){
                debtMap = printDao.getPersonCancel(debt_id);
                url = "print/PersonCancel";
            }
            BigDecimal back_money = (BigDecimal) debtMap.get("back_money");
            if(back_money!=null){
                debtMap.put("back_money",StringUtil.moneyFormat(back_money.toString()));
            }
            BigDecimal back_interest = (BigDecimal) debtMap.get("back_interest");
            if(back_interest!=null){
                debtMap.put("back_interest",StringUtil.moneyFormat(back_interest.toString()));
            }
        }else if("warning".equals(busi_type)){
            if("1".equals(cust_type)){
                debtMap = printDao.getCompanyWarning(debt_id);
                printDao.changeState(debt_id);
                debtMap.put("call", "你单位");
                url = "print/CompanyWarning";
            }else if("0".equals(cust_type)){
                debtMap = printDao.getPersonWarning(debt_id);
                debtMap.put("call", "你");
                url = "print/PersonWarning";
            }
            String contract_name = (String) debtMap.get("contract_name");
            if(!StringUtil.isEmpty(contract_name)){
                List<Map<String,Object>> contracts = jsonToListMap(contract_name);
                debtMap.put("contract_name",contracts);
            }
            BigDecimal principal_sum = (BigDecimal)debtMap.get("principal_sum");
            if(principal_sum!=null){
                debtMap.put("principal_sum",StringUtil.moneyFormat(principal_sum.toString()));
            }
            BigDecimal interest_sum = (BigDecimal)debtMap.get("interest_sum");
            if(interest_sum!=null){
                debtMap.put("interest_sum",StringUtil.moneyFormat(interest_sum.toString()));
            }
            BigDecimal debit_interest = (BigDecimal)debtMap.get("debit_interest");
            if(debit_interest!=null){
                debtMap.put("debit_interest",StringUtil.moneyFormat(debit_interest.toString()));
            }
            BigDecimal total_sum = (BigDecimal)debtMap.get("total_sum");
            if(total_sum!=null){
                debtMap.put("total_sum",StringUtil.moneyFormat(total_sum.toString()));
            }
            String sign_date = (String)debtMap.get("sign_date");
            if(sign_date!=null){
                debtMap.put("sign_date",sign_date.substring(0,4)+"年"+sign_date.substring(4,6)+"月"+sign_date.substring(6,8)+"日");
            }
            System.out.println(request.getAttribute("sign_date"));
        }
        if(debtMap!=null && !debtMap.isEmpty()) {
//            Date data = new Date();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
//            request.setAttribute("today",sdf.format(data));
            Iterator it=debtMap.keySet().iterator();
            String key = null;
            while(it.hasNext()){
                key = it.next().toString();
                request.setAttribute(key,debtMap.get(key));
            }
        }
        return url;
    }

    /**
     * unicode 转码
     * @param json
     * @return
     */
    private List<Map<String, String>> encodeText(String json,String key){
        List<Map<String,String>> list = JSON.parseObject(json, new TypeReference<List<Map<String,String>>>(){});
        for(Map<String,String> map:list){
            map.put(key,StringEscapeUtils.unescapeJava(map.get(key)));
        }
        return list;
    }

    public List<Map<String,Object>> jsonToListMap(Object json){
        List<Map<String,Object>> listMap = new ArrayList<>();
        JSONArray jarr = JSONArray.parseArray((String) json);
        for(Object o:jarr){
            JSONObject job = (JSONObject)o;
            Map<String,Object> debtInfoMap = new HashMap<>();
            for(Map.Entry<String,Object> entry:job.entrySet()){
                if("grt_info".equals(entry.getKey())){
                    debtInfoMap.put(entry.getKey(),jsonToListMap(entry.getValue()));
                }else if("break_date".equals(entry.getKey()) && entry.getValue()!=null) {
                    String break_date = String.valueOf(entry.getValue());
                    debtInfoMap.put(entry.getKey(), break_date.substring(0, 4) + "年" + break_date.substring(4, 6) + "月" + break_date.substring(6, 8) + "日");
                }else if("loan_amount,break_catl,break_intr".contains(entry.getKey()) && entry.getValue()!=null){
                    debtInfoMap.put(entry.getKey(), StringUtil.moneyFormat((String) entry.getValue()));
                }else{
                    debtInfoMap.put(entry.getKey(),entry.getValue());
                }
            }
            listMap.add(debtInfoMap);
        }
        return listMap;
    }
}

